/*
 * Copyright 2011 myTDev.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mytdev.commons.text;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author Yann D'Isanto
 */
public final class EnumParserFactory implements ParserFactory {

    private static final EnumParserFactory INSTANCE = new EnumParserFactory();
    private final Map<Class<? extends Enum>, Parser<? extends Enum>> parsersCache = new HashMap<Class<? extends Enum>, Parser<? extends Enum>>();

    private EnumParserFactory() {
    }

    @Override
    public boolean isTypeSupported(Class<?> type) {
        return Enum.class.isAssignableFrom(type);
    }

    @Override
    public <T> Parser<? extends T> getParser(Class<T> type) {
        if (!Enum.class.isAssignableFrom(type)) {
            throw new IllegalArgumentException("Not an enum type: " + type.getName());
        }
        return (Parser<? extends T>) getEnumParser((Class<? extends Enum>) type);
    }

    private <E extends Enum> Parser<E> getEnumParser(Class<E> type) {
        Parser<E> parser = (Parser<E>) parsersCache.get(type);
        if (parser == null) {
            parser = new EnumParser<E>(type);
            parsersCache.put(type, parser);
        }
        return parser;
    }

    public static EnumParserFactory getInstance() {
        return INSTANCE;
    }
}
